<!-- BP2 血压仪设备 -->
<template>
	<view class="pageview">
		<firstConnect v-if="isFirst" :device-type="deviceType" :deviceStatus="deviceStatus" @startUse="startUse"
			@retry="retry"></firstConnect>
		<template v-else>
			<view class="toptip flex align-center justify-between" v-if="!isConnected">
				<text>{{ blueState ? '当前设备未连接，请连接设备' : '需要开启蓝牙，连接设备' }}</text>
				<view class="btn flex align-center" @click="devicesDiscovery" v-if="blueState">
					<u-loading-icon color="#fff" :show="deviceStatus == 0 || deviceStatus == 1"></u-loading-icon>
					<text>去连接</text>
				</view>
			</view>
			<view class="startWork">
				<div class="blueState u-flex  u-flex-column ">
					<image src="/static/device/bluetooth.png" mode="widthFix" v-if="deviceStatus!=2"></image>
					<image src="/static/device/bluetooth_cur.png" mode="widthFix" v-else></image>
					<span class="name" :class="{'active':deviceStatus==2}">{{deviceStatus==2?"已连接":"未连接"}}</span>
				</div>
				<div class="electricityState">
					<div class="battery-indicator  u-flex  u-flex-column">
						<div class="battery-container" :style="{'--battery-level': batteryValue + '%'}">
							<div class="battery-level" :class="{ 'low-battery': isLowBattery }"></div>
							<div class="battery-head"></div>
						</div>
						<span class="battery-percent" v-if="batteryValue!=null" :class="{ 'low-battery': isLowBattery }">
							{{ batteryValue }}%
						</span>
					</div>
				</div>
				<bpChart ref="bpChart"></bpChart>
				<view class="u-m-t-30" v-if="isConnected&& deviceData.runStatus ==-1">
					<u-button shape="circle" type="primary" text="开始测量" @click="start"></u-button>
				</view>
				<view class="u-m-t-30" v-if="isConnected&& deviceData.runStatus ==0">
					<u-button shape="circle" type="error" text="结束测量" @click="stop"></u-button>
				</view>
				<view v-if="isConnected && deviceData.runStatus ==1">
					<view class="tip">{{ deviceData.systolic_pressure > 0 ? '' : '测量失败' }}</view>
					<template v-if="deviceData.systolic_pressure > 0">
						<view class="stepbox">
							<bpStep size="lg" :systolic_pressure="deviceData.systolic_pressure"
								:diastolic_pressure="deviceData.diastolic_pressure"></bpStep>
						</view>
						<view class="flex result">
							<view class="flex-sub item">
								<view>收缩压</view>
								<view class="u-margin-top-20">
									<text class="num">{{ deviceData.systolic_pressure }}</text>
									<text class="unit">mmHg</text>
								</view>
							</view>
							<view class="flex-sub item">
								<view>舒张压</view>
								<view class="u-margin-top-20">
									<text class="num">{{ deviceData.diastolic_pressure }}</text>
									<text class="unit">mmHg</text>
								</view>
							</view>
							<view class="flex-sub item">
								<view>心率</view>
								<view class="u-margin-top-20">
									<text class="num">{{ deviceData.hr }}</text>
									<text class="unit">次/分钟</text>
								</view>
							</view>
						</view>
						<view class="u-m-t-30 u-flex u-flex-center">
							<view class="u-flex-sub">
								<u-button shape="circle" plain type="primary" text="重新测量" @click="start"></u-button>
							</view>
							<view class="u-flex-sub u-m-l-20"><u-button shape="circle" type="primary" text="保存"
									@click="save"></u-button>
							</view>
						</view>
					</template>
					<view class="tip u-m-t-20">点击血压仪上启动键，重新开始测量</view>
				</view>
			</view>
		</template>
	</view>
</template>

<script>
	import {
		ab2str,
		formatNum,
		formatSecond,
		chunk
	} from '@/utils/util';
	import {
		parsePacket
	} from '@/utils/ble_devices/v3.js';

	const fs = wx.getFileSystemManager();
	const BP2Protocol = require('@/utils/ble_devices/v3');
	let _this = this;
	const BP2Builder = {
		// 注意这里的this是实例化后的BP2对象，而不是page,注意这里服务Id一定要大写，兼容苹果手机
		notifyServiceId: ["0000FFE5-0000-1000-8000-00805F9B34FB", "0000FFE0-0000-1000-8000-00805F9B34FB"],
		deviceFoundFilter: item => /(V03)/.test(item.name),
		connectionStateChange: res => console.log('BP2连接状态改变', res),
		characteristicValueChange: function(res) {
			if (res.value) {
				console.log('这里是原始数据', ab2str(res.value));
				// 开始解析数据
				if (res.value !== this.oldCallbackData) {
					//可能会有重复的包
					this.oldCallbackData = res.value;
					// 而且微信返回的value是ArrayBuffer，所以同样要先转换成str
					this.parseData(ab2str(res.value));
				}
			}
		}
	};

	const BP2 = new BP2Protocol(BP2Builder);
	let foundTimer = null;
	import firstConnect from './components/firstConnect';
	import bpChart from './components/bpChart';
	import stompMixin from '@/common/stompMixin.js';
	import mixin from './mixin.js';
	import bpStep from '@/components/bpStep';
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				isConnected: false, // 是否连接设备
				devicesDiscovered: [], // 设备列表
				connectedDevice: null, // 当前连接设备
				deviceType: 'V3',
				deviceTypeId: '',
				isFirst: true,
				deviceStatus: 0, //0是没有连接，1是正在连接,2，正常，3 断开
				deviceData: {
					runStatus: -1
				},
				blueState: false,
				deviceRunStatus: -1, //0关机，1数据回顾，2充电，3开机预备，4血压测量中，5血压测量结束，6心电测量中，7心电测量结束
				hasSave: 0,
				batteryValue: null,
			};
		},
		mixins: [stompMixin, mixin],
		computed: {
			...mapState(['userInfo', 'curAccount', 'doctorId']),
			isLowBattery() {
				return parseFloat(this.batteryValue) <= 20;
			}
		},
		components: {
			firstConnect,
			bpChart,
			bpStep
		},
		onLoad(optioin) {
			this.deviceType = optioin.deviceType;
			if (optioin.deviceTypeId) {
				this.deviceTypeId = optioin.deviceTypeId;
				this.isFirst = true;
			} else {
				this.deviceMac = optioin.deviceMac;
				this.isFirst = false;
			}
			// 使用 watch 方法监听 message 属性的变化
			const appInstance = getApp();
			appInstance.watch(this, BP2, {
				//蓝牙配置状态
				adapterState: function(newVal) {
					if (newVal && !this.blueState) {
						this.blueState = true; //设置蓝牙初始化成功了
						this.deviceStatus = -1;
						if (this.isFirst) {
							this.devicesDiscovery();
						}
					}
				},
				foundDevices: function(newVal) {
					console.log('this.devicesDiscovered', this.devicesDiscovered)
					this.devicesDiscovered = newVal;
					if (this.devicesDiscovered.length > 0 && !this.isConnected) {
						let index = -1;
						if (this.deviceMac) {
							index = this.devicesDiscovered.findIndex(item => item.deviceId == this.deviceMac);
						} else {
							index = this.devicesDiscovered.findIndex(item => /(V03)/.test(item.name));
						}
						console.log('index', index);
						if (index > -1) {
							this.deviceStatus = 1;
							this.connectToDevice(index);
							clearTimeout(foundTimer);
							foundTimer = null;
						}
					}
				},
				connectedDevice: function(newVal) {
					console.log('连接设备newVal', newVal);
					this.isConnected = !!newVal;
					this.connectedDevice = newVal;
					if (!!newVal) {
						this.deviceStatus = 2;
						if (this.isFirst) {
							this.addDevice();
						}
					}
				},
				deviceRunInfo: function(newVal, oldVal) {
					console.log('设备运行newVal', newVal)
					this.deviceData = newVal;
					if (newVal && JSON.stringify(newVal) != JSON.stringify(oldVal)) {
						if (this.deviceData.runStatus == 0) {
							this.$refs.bpChart && this.$refs.bpChart.getServerData(newVal.pressure);
						}
					}
				},
				//电量
				battery: function(newVal, oldVal) {
					console.log("电量呀" + newVal)
					this.batteryValue = newVal;
					if (newVal) {
						this.send_testtwo(
							JSON.stringify({
								oprDocterID: this.doctorId,
								mac: this.deviceMac,
								type: 'Electric',
								value: this.batteryValue
							})
						);
					}
				}

			});
			// 开启监听ER2属性
			// this.watchER2()
			// 初始化蓝牙
			BP2.init();
		},
		onUnload() {
			// 不在当前页面的时候断开连接
			this.disconnectToDevice();
			if (foundTimer || this.deviceStatus == 0) {
				this.clearfoundTimer();
			}
		},

		methods: {
			// 搜索周围设备
			devicesDiscovery() {
				this.deviceStatus = 0;
				BP2.startDevicesDiscovery();
				//5s没有找到设备，就提示没有发现设备
				foundTimer = setTimeout(() => {
					this.clearfoundTimer();
				}, 5000);
			},
			// 连接指定设备
			connectToDevice(index) {
				BP2.stopDevicesDiscovery();
				const targetDevice = this.devicesDiscovered[index];
				BP2.connectToDevice(targetDevice).then(() => {
					// 连接成功后获取设备信息
					// const cmd = BP2.generateCmd(0x01, []);
					// BP2.writeValue(cmd);
					/* 获取电量 */
					const EcgCmd = BP2.generateCmd(0x40, []); // BP2实时的指令是08，type是00，data是空，由于指令有流水号，所以每次都要重新生成
					BP2.writeValue(EcgCmd);
					console.log("发送电量指令了吗")
				});
			},
			// 断开当前连接设备
			disconnectToDevice() {
				BP2.disconnectToDevice();
			},
			//重新开始测量
			resume() {
				this.deviceData.pressure = 0;
				this.deviceData.runStatus = 0;
				//this.getRealTimeEcg();
			},
			startUse() {
				this.isFirst = false;

			},
			retry() {
				this.deviceStatus = 0;
				this.devicesDiscovery();
			},
			clearfoundTimer() {
				BP2.stopDevicesDiscovery();
				clearTimeout(foundTimer);
				foundTimer = null;
				this.deviceStatus = 3;
			},
			save() {
				console.log("到这里了吗")
				/* this.send(
					JSON.stringify({
						//detailId: this.curAccount.detailId,
						patientId:this.curAccount.patientId,
						type: 'BP2',
						data: BP2.deviceRunInfo
					})
				); */
				this.send_testtwo(
					JSON.stringify({
						oprDocterID: this.doctorId,
						patientId: this.curAccount.patientId,
						type: 'BP2',
						data: BP2.deviceRunInfo
					})
				);
				uni.showToast({
					title: '保存成功',
					icon: 'none'
				})
				this.$Router.replaceAll({
					path: '/pages/measure/measure'
				});
			},
			start() {
				const EcgCmd = BP2.generateCmd(0x11, []); // BP2实时的指令是08，type是00，data是空，由于指令有流水号，所以每次都要重新生成
				BP2.writeValue(EcgCmd);
			},
			stop() {
				const EcgCmd = BP2.generateCmd(0x10, []); // BP2实时的指令是08，type是00，data是空，由于指令有流水号，所以每次都要重新生成
				BP2.writeValue(EcgCmd);
			}
		}
	};
</script>

<style scoped lang="scss">
	.pageview {
		background: #f2f2f2;
		height: 100vh;
		overflow: auto;
	}

	.startWork {
		width: 600upx;
		margin: 0 auto;
		padding-top: 180upx;
		position: relative;

		.blueState {
			position: absolute;
			left: 0;
			top: 140upx;

			//top: 160upx;
			image {
				width: 60upx;
				height: 60upx;
				margin: 0 auto;
			}

			.name {
				color: #999;
				margin-top: 10upx;
				font-size: 30upx;

				&.active {
					color: #36B7AB;
				}
			}
		}

		.electricityState {
			position: absolute;
			right: 0;
			top: 160upx;

			image {
				width: 60upx;
				height: 60upx;
			}
		}

		.imgbox {
			width: 400upx;
			margin: 0 auto 70upx;
		}

		.tip {
			text-align: center;
			margin-bottom: 10upx;
		}

		.stepbox {
			margin-top: 50upx;
		}

		.result {
			background: #fff;
			border-radius: 16upx;
			font-size: 28upx;
			color: #a5adae;
			padding: 30upx 20upx;
			margin-top: 50upx;

			.item {
				padding: 0 16upx;
			}

			.num {
				color: #243138;
				font-size: 46upx;
				font-weight: bold;
			}

			.unit {
				color: #374547;
				font-size: 24upx;
				margin-left: 10upx;
			}
		}
	}

	.toptip {
		background: #fff;
		padding: 20upx;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;

		.btn {
			background: $u-primary;
			padding: 0 20upx;
			color: #fff;
			border-radius: 50upx;
			line-height: 60upx;
		}
	}

	.battery-container {
		--battery-level: 15%;
		display: inline-block;
		position: relative;
		/* width: 60px;
	  height: 30px; */
		width: 40px;
		height: 20px;
		border: 2px solid #333;
		border-radius: 3px;
		background: #f5f5f5;
		margin-right: 5px;
		transform: rotate(-90deg);
	}

	.battery-head {
		position: absolute;
		right: -6px;
		//top: 7px;
		top: 2px;
		width: 4px;
		height: 12px;
		background: #333;
		border-radius: 0 2px 2px 0;
	}

	.battery-level {
		position: absolute;
		left: 2px;
		top: 2px;
		bottom: 2px;
		width: var(--battery-level);
		//background: var(--battery-color, #4CAF50);
		background: #4CAF50;
		border-radius: 1px;
	}

	.battery-percent {
		display: inline-block;
		font-family: Arial, sans-serif;
		font-size: 14px;
		vertical-align: middle;
		color: #333;
		font-weight: bold;
		margin-top: 12px;
		text-align: center;
	}

	.low-battery {
		color: #ff4444;
	}

	/* 低电量样式 */
	.battery-container .battery-level {

		animation: pulse 1.5s infinite;

		&.low-battery {
			background: #ff4444;
		}
	}

	@keyframes pulse {
		0% {
			opacity: 1;
		}

		50% {
			opacity: 0.6;
		}

		100% {
			opacity: 1;
		}
	}
</style>